package com.wunu.smartlock1.activity;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.wunu.smartlock1.R;
import com.wunu.smartlock1.bluetooth.WunuBlueManager;
import com.wunu.smartlock1.bluetooth.command.BindLockCommand;
import com.wunu.smartlock1.bluetooth.command.CheckBindCommand;
import com.wunu.smartlock1.net.NetComponent;
import com.wunu.smartlock1.net.api.LockManageApi;
import com.wunu.smartlock1.net.param.BindLockParam;
import com.wunu.smartlock1.net.response.ApiNormalResponse;
import com.wunu.smartlock1.net.response.BindLockResult;
import com.wunu.smartlock1.util.CommonUtil;

import retrofit2.Call;


/**
 * 扫描搜索到设备后点击绑定
 * Created by admin on 2018/4/21.
 */

public class LockBindActivity_sync_bak extends AppCompatActivity{
    Button bindButton;
    BindLockParam param;

    TextView lockMac;
    TextView lockName;
    TextView lockNote;
    ImageView lockImage;
    Intent intent = new Intent();
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg){
            System.out.println("msg----------------------->:"+msg);
            ApiNormalResponse<BindLockResult> resp =(ApiNormalResponse<BindLockResult>) msg.obj;
            System.out.println("code:"+resp.getCode());
            if (resp == null || resp.getCode()!=0 || resp.getData().getCode()!=200){
                Toast.makeText(LockBindActivity_sync_bak.this, "绑定失败:"+resp.getErrorMsg(), Toast.LENGTH_SHORT).show();
                return;
            }
            //返回的结果: BindLockBean{lockId=78, managerId=90}
            Toast.makeText(LockBindActivity_sync_bak.this, resp.getData().getMsg(), Toast.LENGTH_SHORT).show();
        }
    };
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new MyTask().execute();
        setContentView(R.layout.smartlock_activity_bindlock);
        bindButton = findViewById(R.id.bindButton);
        lockMac = findViewById(R.id.lockMac);
        lockName = findViewById(R.id.lockName);
        lockNote = findViewById(R.id.lockNote);
        lockImage = findViewById(R.id.lockImage);

       bindButton.setOnClickListener(new View.OnClickListener() {
           int baseCode = 648846;
           int openId = 123;
           @Override
           public void onClick(View v) {
               System.out.println("点击了绑定按钮:");
               param = new BindLockParam.Builder()
                       .setBasecode(baseCode)
                       .setLockModel(1)//锁类型
                       .setLockMac(lockMac.getText().toString())//DF:ED:67:87:01:32
                       .setLockName(lockName.getText().toString())
                       .setLockNote(lockNote.getText().toString())//锁申请公告
                       .setLockImageUrl("lock_3.png")//./../../images/lock_3.png
                       .build();
               System.out.println("param:"+param);
               final LockManageApi service = NetComponent.getRetrofit().create(LockManageApi.class);

               BindLockCommand blc = new BindLockCommand(baseCode,openId);

               //开线程加载数据
               new Thread() {
                   @Override
                   public void run() {
                       super.run();
                       try{
                           Call<ApiNormalResponse<BindLockResult>> call = service.bindLock(param);
                           ApiNormalResponse<BindLockResult> resp = call.execute().body();
                           System.out.println("resp: "+resp);
                           // 发送消息，把服务器返回的本文弹出吐司显示
                           Message msg = handler.obtainMessage();
                           msg.obj = resp;
                           handler.sendMessage(msg);
                       } catch (Exception e) {
                           System.out.println("锁绑定异常:" + e);
                       }
                   }
               }.start();
           }
       });
    }

    /**
     * 指定设备进行蓝牙异步交互，获取蓝牙信息
     */
    private class MyTask extends AsyncTask {
        //后台线程执行时
        @Override
        protected Object doInBackground(Object... params) {
            System.out.println("蓝牙名称:"+ CommonUtil.device.getName()+"\tmac:"+CommonUtil.device.getMac());
            CheckBindCommand cmd = new CheckBindCommand();
            WunuBlueManager manager = new WunuBlueManager();
            manager.setCommand(cmd);
            manager.connectDevice(CommonUtil.device);

            System.out.println("map:"+CommonUtil.map);
            while (CommonUtil.map == null) {
                try {
                    Thread.sleep(100);
                } catch (Exception e) {
                }
            }
            return null;
        }

        //后台线程执行结束后的操作，其中参数result为doInBackground返回的结果
        @Override
        protected void onPostExecute(Object result) {
            super.onPostExecute(result);
            System.out.println("msg----------task------------->:"+CommonUtil.map);

            System.out.println(CommonUtil.map);
            if(!CommonUtil.map.containsKey("state")){
                Toast.makeText(LockBindActivity_sync_bak.this, "未获取到蓝牙绑定状态!", Toast.LENGTH_SHORT).show();
                CommonUtil.map = null;
                return;
            }
            /*if((boolean)CommonUtil.map.get("state")){
                Toast.makeText(LockBindActivity.this, "该锁已被绑定", Toast.LENGTH_SHORT).show();
                CommonUtil.map = null;
                LockBindActivity.this.finish();
                return;
            }*/
            String mac = (String)CommonUtil.map.get("mac");
            System.out.println("mac:"+mac);
            lockMac.setText(mac);
            System.out.println("msg-----------------end->:"+CommonUtil.map);
            CommonUtil.map = null;
            System.out.println("order map :"+CommonUtil.map);
        }
    }
}
